<template>
  <div class="component-upload-image">
    <div class="upload-container">
      <el-upload
          ref="upload"
          :multiple="false"
          :action="uploadFileUrl"
          list-type="picture-card"
          :on-success="handleUploadSuccess"
          :before-upload="handleBeforeUpload"
          :limit="1"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          name="file"
          :on-remove="handleRemove"
          :show-file-list="true"
          :headers="headers"
          :file-list="fileList"
          :class="{hide: this.fileList.length >= 1}"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <!-- 添加可点击的图片显示区域 -->
      <div v-if="fileList.length > 0" class="image-preview" @click="triggerUpload">
        <img :src="fileList[0].url" alt="属性图片" class="preview-image">
        <div class="image-mask">
          <i class="el-icon-edit"></i>
        </div>
      </div>
    </div>

    <!-- 隐藏的文件输入框 -->
    <input
      ref="fileInput"
      type="file"
      style="display: none"
      accept="image/*"
      @change="handleFileChange"
    >

    <!-- 恢复上传提示 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
      的文件
    </div>
  </div>
</template>

<script>
import { getAccessToken } from "@/utils/auth";
import { upload } from "@/api/infra/file";

export default {
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    isShowTip: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      hideUpload: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload",
      headers: { Authorization: "Bearer " + getAccessToken() },
      fileList: []
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let list;
          if (Array.isArray(val)) {
            list = val;
          } else if (typeof val === 'string') {
            list = [val];
          } else {
            list = [];
          }
          // 过滤掉空值并确保每个项都是字符串
          this.fileList = list
            .filter(item => item && typeof item === 'string' && item.trim() !== '')
            .map(item => ({ name: item, url: item }));
        } else {
          this.fileList = [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 触发文件选择
    triggerUpload() {
      this.$refs.fileInput.click();
    },

    // 处理文件选择变化
    async handleFileChange(e) {
      const file = e.target.files[0];
      if (!file) return;
      
      // 验证文件
      if (!this.validateFile(file)) {
        // 清空文件输入框，以便能够重新选择同一文件
        this.$refs.fileInput.value = '';
        return;
      }

      // 显示上传loading
      this.$modal.loading("正在上传图片，请稍候...");

      try {
        // 创建 FormData
        const formData = new FormData();
        formData.append('file', file);
        
        // 使用配置好的上传接口
        const res = await upload(formData);
        
        // 处理上传结果
        if (res.code === 0 && res.data) {
          // 更新 fileList
          this.fileList = [{ name: res.data, url: res.data }];
          // 触发 input 事件，发送新的图片 URL
          this.$emit("input", [res.data]);
        } else {
          throw new Error(res.msg || "上传失败");
        }
      } catch (error) {
        this.$modal.msgError(error.message || "上传图片失败，请重试");
      } finally {
        this.$modal.closeLoading();
        // 清空文件输入框，以便能够重新选择同一文件
        this.$refs.fileInput.value = '';
      }
    },

    // 验证文件
    validateFile(file) {
      // 验证文件类型
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          return !!(fileExtension && fileExtension.indexOf(type) > -1);
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }

      // 验证文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }

      return true;
    },

    // 删除图片
    handleRemove(file) {
      this.fileList = [];
      this.$emit("input", []);
    },
    // 上传成功回调
    handleUploadSuccess(res) {
      if (res.code === 0 && res.data) {
        this.fileList = [{ name: res.data, url: res.data }];
        this.$emit("input", res.data);
          this.$modal.closeLoading();
      } else {
        this.$modal.msgError(res.msg || "上传失败");
        this.$modal.closeLoading();
      }
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          return !!(fileExtension && fileExtension.indexOf(type) > -1);
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      return true;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`只能上传1张图片!`);
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    }
  }
};
</script>
<style scoped lang="scss">
.component-upload-image {
  width: 100%;
}

// 恢复原80x80样式
:deep(.el-upload--picture-card) {
  width: 40px !important;
  height: 40px !important;
  line-height: 40px !important;
}

:deep(.el-upload-list--picture-card) {
  display: inline-flex;
  flex-wrap: nowrap;
  margin: 0;
  padding: 0;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 40px !important;
  height: 40px !important;
  margin: 0 !important;
}

:deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-container {
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  padding-bottom: 10px;
  scrollbar-width: thin;
  scrollbar-color: #909399 #f4f4f5;

  &::-webkit-scrollbar {
    height: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f4f4f5;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: #909399;
    border-radius: 3px;
  }
}

// .el-upload--picture-card 控制加号部分
:deep(.hide .el-upload--picture-card) {
  display: none;
}

// 去除动画效果
:deep(.el-list-enter-active),
:deep(.el-list-leave-active),
:deep(.el-list-enter),
:deep(.el-list-leave-active) {
  transition: none !important;
  opacity: 1 !important;
  transform: none !important;
}

.image-preview {
  position: relative;
  display: inline-block;
  width: 40px;
  height: 40px;
  cursor: pointer;
  vertical-align: top;
  margin-right: 8px;

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .image-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;

    i {
      color: #fff;
      font-size: 16px;
    }
  }

  &:hover .image-mask {
    opacity: 1;
  }
}

// 隐藏el-upload的默认显示
:deep(.el-upload-list--picture-card) {
  display: none;
}
</style>

